<template>
  <div class="security-events">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="title">安全事件</span>
        <el-button-group class="header-operations">
          <el-button type="primary" icon="el-icon-refresh" size="small" @click="refreshData">刷新</el-button>
          <el-button type="success" icon="el-icon-download" size="small" @click="exportData">导出</el-button>
        </el-button-group>
      </div>

      <!-- Event Statistics -->
      <el-row :gutter="20" class="event-statistics">
        <el-col :span="6" v-for="(stat, index) in statistics" :key="index">
          <el-card shadow="hover" :body-style="{ padding: '20px' }">
            <div class="statistic-item">
              <div class="statistic-icon" :class="stat.type">
                <i :class="stat.icon"></i>
              </div>
              <div class="statistic-info">
                <div class="statistic-title">{{ stat.title }}</div>
                <div class="statistic-value">{{ stat.value }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- Search and Filter -->
      <div class="search-filter">
        <el-input
          v-model="searchQuery"
          placeholder="搜索客户名称/IP/事件"
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearchClear"
          style="width: 300px;"
        >
        </el-input>
        <el-select v-model="urgencyFilter" placeholder="紧急程度" clearable style="width: 120px;">
          <el-option label="高" value="高"></el-option>
          <el-option label="中" value="中"></el-option>
          <el-option label="低" value="低"></el-option>
        </el-select>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
        >
        </el-date-picker>
      </div>

      <!-- Main Table -->
      <el-table
        :data="filteredTableData"
        style="width: 100%"
        v-loading="loading"
        :empty-text="emptyText"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="clientName" label="客户名称" min-width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="serverIp" label="影响服务器" min-width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="eventName" label="事件名称" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="urgencyLevel" label="紧急程度" width="120">
          <template slot-scope="scope">
            <el-tag :type="getUrgencyType(scope.row.urgencyLevel)" size="small">
              {{ scope.row.urgencyLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="triggerTime" label="触发时间" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template slot-scope="scope">
            <el-button @click="handleDetails(scope.row)" type="text" size="small">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Batch Operations -->
      <div class="batch-operations" v-if="selectedEvents.length > 0">
        <el-button type="primary" size="small" @click="handleBatchProcess">批量处理</el-button>
        <el-button type="danger" size="small" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <!-- Pagination -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- Event Trend Chart -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="title">安全事件趋势</span>
      </div>
      <div id="eventTrendChart" style="width: 100%; height: 300px;"></div>
    </el-card>

    <!-- Details Dialog -->
    <el-dialog
      title="安全事件详情"
      :visible.sync="detailsVisible"
      width="50%">
      <el-descriptions :column="1" border v-if="selectedEvent">
        <el-descriptions-item label="客户名称">{{ selectedEvent.clientName }}</el-descriptions-item>
        <el-descriptions-item label="影响服务器">{{ selectedEvent.serverIp }}</el-descriptions-item>
        <el-descriptions-item label="事件名称">{{ selectedEvent.eventName }}</el-descriptions-item>
        <el-descriptions-item label="紧急程度">
          <el-tag :type="getUrgencyType(selectedEvent.urgencyLevel)" size="small">
            {{ selectedEvent.urgencyLevel }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="触发时间">{{ selectedEvent.triggerTime }}</el-descriptions-item>
        <el-descriptions-item label="事件描述">{{ selectedEvent.description || '暂无描述' }}</el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailsVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleProcess">处理事件</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'SecurityEvents',
  data() {
    return {
      searchQuery: '',
      urgencyFilter: '',
      dateRange: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      detailsVisible: false,
      selectedEvent: null,
      emptyText: '暂无安全事件',
      selectedEvents: [],
      statistics: [
        { title: '总事件数', value: 0, icon: 'el-icon-warning', type: 'total' },
        { title: '高危事件', value: 0, icon: 'el-icon-danger', type: 'high' },
        { title: '中危事件', value: 0, icon: 'el-icon-warning', type: 'medium' },
        { title: '低危事件', value: 0, icon: 'el-icon-info', type: 'low' }
      ],
      chart: null
    }
  },
  computed: {
    filteredTableData() {
      return this.tableData.filter(item => {
        const matchSearch = !this.searchQuery ||
          item.clientName.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
          item.serverIp.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
          item.eventName.toLowerCase().includes(this.searchQuery.toLowerCase());

        const matchUrgency = !this.urgencyFilter || item.urgencyLevel === this.urgencyFilter;

        const matchDate = !this.dateRange.length ||
          (new Date(item.triggerTime) >= new Date(this.dateRange[0]) &&
            new Date(item.triggerTime) <= new Date(this.dateRange[1]));

        return matchSearch && matchUrgency && matchDate;
      });
    }
  },
  methods: {
    getUrgencyType(level) {
      const types = { '高': 'danger', '中': 'warning', '低': 'info' };
      return types[level] || 'info';
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    handleDetails(row) {
      this.selectedEvent = row;
      this.detailsVisible = true;
    },
    handleProcess() {
      this.$message({ type: 'success', message: '事件处理中...' });
      this.detailsVisible = false;
    },
    handleSearchClear() {
      this.searchQuery = '';
      this.fetchData();
    },
    handleDateChange() {
      this.fetchData();
    },
    handleSelectionChange(val) {
      this.selectedEvents = val;
    },
    handleBatchProcess() {
      this.$message({ type: 'success', message: `正在批量处理 ${this.selectedEvents.length} 个事件` });
    },
    handleBatchDelete() {
      this.$confirm(`确定要删除选中的 ${this.selectedEvents.length} 个事件吗？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({ type: 'success', message: '删除成功' });
        // 实现实际的删除逻辑
      }).catch(() => {});
    },
    refreshData() {
      this.fetchData();
    },
    exportData() {
      this.$message({ type: 'success', message: '正在导出数据...' });
      // 实现实际的导出逻辑
    },
    async fetchData() {
      this.loading = true;
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        // 这里应该是实际的API调用
        this.tableData = [
          { clientName: '示例客户1', serverIp: '192.168.1.1', eventName: '异常登录尝试', urgencyLevel: '高', triggerTime: '2024-02-27 14:30:00', description: '检测到多次失败的登录尝试' },
          { clientName: '示例客户2', serverIp: '192.168.1.2', eventName: '可疑文件访问', urgencyLevel: '中', triggerTime: '2024-02-27 15:45:00', description: '检测到对敏感文件的异常访问' },
          { clientName: '示例客户3', serverIp: '192.168.1.3', eventName: '系统配置更改', urgencyLevel: '低', triggerTime: '2024-02-27 16:20:00', description: '检测到未经授权的系统配置更改' },
          // 添加更多示例数据...
        ];
        this.total = this.tableData.length;
        this.updateStatistics();
        this.updateChart();
      } catch (error) {
        this.$message.error('获取数据失败');
      } finally {
        this.loading = false;
      }
    },
    updateStatistics() {
      const stats = { total: 0, high: 0, medium: 0, low: 0 };
      this.tableData.forEach(item => {
        stats.total++;
        if (item.urgencyLevel === '高') stats.high++;
        else if (item.urgencyLevel === '中') stats.medium++;
        else if (item.urgencyLevel === '低') stats.low++;
      });
      this.statistics[0].value = stats.total;
      this.statistics[1].value = stats.high;
      this.statistics[2].value = stats.medium;
      this.statistics[3].value = stats.low;
    },
    updateChart() {
      if (!this.chart) {
        this.chart = echarts.init(document.getElementById('eventTrendChart'));
      }
      const option = {
        title: { text: '近7天安全事件趋势' },
        tooltip: { trigger: 'axis' },
        legend: { data: ['高危', '中危', '低危'] },
        xAxis: { type: 'category', data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] },
        yAxis: { type: 'value' },
        series: [
          { name: '高危', type: 'line', data: [5, 7, 3, 8, 6, 2, 4] },
          { name: '中危', type: 'line', data: [10, 12, 8, 9, 11, 7, 10] },
          { name: '低危', type: 'line', data: [15, 14, 18, 16, 13, 17, 15] }
        ]
      };
      this.chart.setOption(option);
    }
  },
  mounted() {
    this.fetchData();
    window.addEventListener('resize', () => {
      if (this.chart) {
        this.chart.resize();
      }
    });
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  }
}
</script>

<style scoped>
.security-events {
  padding: 8px;
}

.box-card {
  margin-bottom: 10px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-operations {
  float: right;
}

.event-statistics {
  margin-bottom: 20px;
}

.statistic-item {
  display: flex;
  align-items: center;
}

.statistic-icon {
  font-size: 24px;
  margin-right: 10px;
}

.statistic-icon.total { color: #409EFF; }
.statistic-icon.high { color: #F56C6C; }
.statistic-icon.medium { color: #E6A23C; }
.statistic-icon.low { color: #67C23A; }

.statistic-info {
  display: flex;
  flex-direction: column;
}

.statistic-title {
  font-size: 14px;
  color: #606266;
}

.statistic-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.search-filter {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.batch-operations {
  margin-top: 10px;
  margin-bottom: 10px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .event-statistics {
    flex-direction: column;
  }

  .search-filter {
    flex-direction: column;
  }

  .search-filter > * {
    margin-bottom: 10px;
    width: 100% !important;
  }

  .header-operations {
    float: none;
    margin-top: 10px;
  }
}
</style>
